<template>
  <div class="app-container">
    <el-row>
      <el-col>
        <el-form
          :model="queryParams"
          ref="queryForm"
          v-show="showSearch"
          :inline="true"
        >
          <el-form-item label="所属商户" prop="merchantId">
            <el-select v-model="queryParams.shopId" placeholder="请选择所属商家" clearable filterable
                       size="small" >
              <el-option  v-for="shop in shopList"
                          :key="shop.id"
                          :label="shop.name"
                          :value="shop.id" />
            </el-select>
          </el-form-item>

          <el-form-item label="资源名称" prop="groupName">
            <el-input
              v-model="queryParams.resourceName"
              placeholder="资源名称"
              clearable
              size="small"
              style="width: 160px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="横纵向状态" prop="format">
            <el-select
              v-model="queryParams.format"
              placeholder="横纵向状态"
              clearable
            >
              <el-option
                v-for="dict in formatStatus"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否是碎片" prop="isFrag">
            <el-select
              v-model="queryParams.isFrag"
              placeholder="请选择状态"
              clearable
            >
              <el-option
                v-for="dict in fragStatus"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['resource:resource:add']"
          >新增
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['resource:resource:remove']"
          >删除
        </el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商户名称" align="center" prop="shopName" />
      <el-table-column label="资源名称" align="center" prop="resourceName" />
      <el-table-column label="资源分组名称" align="center" prop="groupName" />
      <el-table-column
        label="资源地址"
        align="center"
        prop="resourceUrl"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            @click="playVideo(scope.row)"
            ref="btn"
            size="mini"
          >
            播 放
          </el-button>
          <!-- <a v-for="url in scope.row.resourceUrlArry" style="color: #00afff;display: block;" :href="url"
             target="view_window">{{url}}</a> -->
        </template>
      </el-table-column>
      <el-table-column label="资源类型" align="center" prop="resourceType">
        <template slot-scope="scope">
          <span v-if="scope.row.resourceType == 0">图片</span>
          <span v-if="scope.row.resourceType == 1">视频</span>
          <span v-if="scope.row.resourceType == 2">音频</span>
        </template>
      </el-table-column>
      <el-table-column label="播放时长" align="center" prop="durationStr" />
      <el-table-column label="是否是碎片" align="center" prop="isFrag">
        <template slot-scope="scope">
          <span>{{ scope.row.isFrag == 0 ? "是" : "否" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="横/纵向" align="center" prop="format">
        <template slot-scope="scope">
          <span>{{ scope.row.format == 0 ? "纵向" : "横向" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="status">
        <template slot-scope="scope">
          <span v-if="scope.row.status == 0">待审核</span>
          <span v-if="scope.row.status == 1">已通过</span>
          <span v-if="scope.row.status == 2">未通过</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        width="300"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['resource:resource:edit']"
            >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['resource:resource:remove']"
            >删除
          </el-button>
          <el-button
            v-if="scope.row.status == 0 && rolesKey == '00'"
            size="mini"
            type="text"
            icon="el-icon-takeaway-box"
            @click="toExamine(scope.row)"
            v-hasPermi="['resource:resource:editStatus']"
            >审核
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      title
      :visible.sync="dialogPlay"
      width="30%"
      @close="closeDialog()"
    >
      <video
        :src="url"
        controls
        autoplay
        class="video"
        width="100%"
      ></video>
    </el-dialog>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改资源对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="600px"
      :show-close="false"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="商户" v-if="rolesKey == '00'">
          <el-select
            v-model="form.shopId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入搜索商户并选择"
            @change="changeShop"
            :remote-method="remoteMethod"
            :loading="loading"
          >
            <el-option
              v-for="item in shopList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分组" prop="groupId">
          <el-select v-model="form.groupId" placeholder="请选择分组">
            <el-option
              v-for="item in groupList"
              :key="item.id"
              :label="item.groupName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="资源名称" prop="resourceName">
          <el-input v-model="form.resourceName" />
        </el-form-item>
        <el-form-item label="是否是视频片段" prop="isFrag">
          <el-select v-model="form.isFrag" @change="isFragChange">
            <el-option
              v-for="dict in fragStatus"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <template v-if="form.isFrag == 1">
          <el-form-item label="资源类型" prop="resourceType">
            <el-select v-model="form.resourceType">
              <el-option
                v-for="dict in resourceType"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </template>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" />
        </el-form-item>
        <el-form-item
          label="上传资源"
          v-if="form.isFrag == 1 || form.isFrag == 0"
        >
          <fileUpload
            v-model="form.resourceUrl"
            :fileSize="fileSize"
            :limit="limitNum"
            @delUrl="delFileUrl"
            :fileType="['mp4']">
          </fileUpload>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 审核对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="openExamine"
      width="1000px"
      append-to-body
    >
      <el-form ref="form" :model="examineForm" label-width="110px">
        <el-form-item label="商户名称:" prop="shopName">
          <span>{{ examineForm.shopName }}</span>
        </el-form-item>
        <el-form-item label="资源名称 :" prop="shopName">
          <span>{{ examineForm.shopName }}</span>
        </el-form-item>
        <el-form-item label="资源分组名称 :" prop="groupName">
          <span>{{ examineForm.groupName }}</span>
        </el-form-item>
        <el-form-item label="资源地址 :" prop="resourceUrl">
          <span>{{ examineForm.resourceUrl }}</span>
        </el-form-item>
        <el-form-item label="资源类型 :" prop="resourceType">
          <span v-if="examineForm.resourceType == 0">图片</span>
          <span v-if="examineForm.resourceType == 1">视频</span>
          <span v-if="examineForm.resourceType == 2">音频</span>
        </el-form-item>
        <el-form-item label="播放时长 :" prop="durationStr">
          <span>{{ examineForm.durationStr }}</span>
        </el-form-item>
        <el-form-item label="是否是碎片 :" prop="isFrag">
          <span>{{ examineForm.isFrag == 0 ? "是" : "否" }}</span>
        </el-form-item>
        <el-form-item label="横/纵向 :" prop="format">
          <span>{{ examineForm.format == 0 ? "纵向" : "横向" }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="AuditSuccess" style="float: left"
          >通 过</el-button
        >
        <el-button @click="turnDown">驳 回</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, resourceAdd, resourceEdit, resourceDel, info, selectList, examine,deleteFile } from '@/api/resource/resource'
import { mapState } from 'vuex'
import { listUser ,listAllShop} from '@/api/merchant/merchant'
import fileUpload from '@/components/FileUpload/index'

export default {
  name: "class",
  components: {
    fileUpload: fileUpload,
  },
  data() {
    return {
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      //视频弹窗
      dialogPlay: false,
      //视频地址
      url: "",
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //是否显示核销对话框
      openExamine: false,
      // 是否显示分组列表弹出层
      groupOpen: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      //分组资源查询参数
      queryGroup: {
        pageNum: 1,
        pageSize: 10,
      },
      //查看分组弹窗表格
      groupList: [],
      //横纵向类型
      formatStatus: [
        { id: "0", name: "纵向" },
        { id: "1", name: "横向" },
      ],
      //碎片类型
      fragStatus: [
        { dictValue: 0, dictLabel: "是" },
        { dictValue: 1, dictLabel: "否" },
      ],
      //资源类型
      resourceType: [
        // { id: 0, name: "图片" },
        { id: 1, name: "视频" },
        { id: 2, name: "音频" },
      ],
      dateRange: [],
      //状态字典
      statusOptions: [],
      //商户类型字典
      resourceTypeOptions: [],
      // 表单参数
      form: {},
      //审核表单
      examineForm: {},
      // 表单校验
      rules: {
        groupId: [{ required: true, message: "分组不能为空" }],
        resourceType: [{ required: true, message: "请选择资源类型" }],
        resourceName: [
          { min: 2, message: "名称最少两个字符", trigger: "blur" },
        ],
        isFrag: [{ required: true, message: "该选项不能为空" }],
      },
      //商户id（用于新增操作）
      shopID: "",
      //分组总数
      groupTotal: "",
      //商户列表
      shopList: [],
      // 上传资源参数
      fileList: [],
      dialogResourceUrl: "",
      dialogVisible: false,
      disabled: false,
      uploadFileUrl: process.env.VUE_APP_BASE_URL + "/common/video/upload", // 上传的图片服务器地址
      limitNum: 1,
      fileSize: 10,
      //审核需要的资源id
      resourceId:'',
      //保存删除文件url地址
      deleteFileUrl:[],
      //商户列表

    }
  },
  computed: {
    ...mapState({
      rolesKey: (state) => state.user.rolesKey,
    }),
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then((response) => {
      this.statusOptions = response.data;
      this.statusOptions.forEach((item) => {
        item.dictValue = Number(item.dictValue);
      });
    });
    this.getAllShop();
  },
  methods: {
    /**查询所有商户列表*/
    getAllShop(){
      this.loading = true;
      listAllShop().then(
        (response) => {
          this.shopList = response.data;
          this.loading = false;
        }
      );
    },
    getList() {
      this.loading = true;
      list(this.queryParams).then((response) => {
        this.list = response.rows;
        this.list.forEach((item) => {
          item.resourceUrlArry = item.resourceUrl.split(",");
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    //选中商户函数
    changeShop(e) {
      this.getGroupList(e);
    },
    //商户资源分组列表
    getGroupList(id) {
      let shopId = {};
      if (id) {
        shopId = {
          shopId: id,
        };
      } else {
        shopId = {};
      }
      selectList(shopId).then((response) => {
        this.groupList = response.rows;
      });
    },
    //搜索商户方法
    remoteMethod(query) {
      listUser({
        shopName: query,
      }).then((res) => {
        this.shopList = res.rows;
      });
      // console.log(query);
    },
    //根据是否选择碎片
    isFragChange(e) {
      if (e == 0) {
        this.fileSize = 10;
      } else {
        this.fileSize = 50;
      }
    },
    //获取删除url地址
    delFileUrl(url){
      this.deleteFileUrl.push(url);
      console.log(this.deleteFileUrl);
      // console.log(this.deleteFileUrl)
      this.form.resourceUrl = "";
    },
    // 表单重置
    reset() {
      this.form = {};
      this.deleteFileUrl = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {};
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.open = true;
      this.title = "添加资源";
      this.limitNum = 10;
      if (this.rolesKey != "00") {
        this.getGroupList();
      }

      // this.form.shopId = row.id || this.shopID
    },

    /** 查看商户资源分组操作 */
    handleList(row) {
      this.reset();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      info(id).then((response) => {
        this.form = response.data;
        this.remoteMethod(response.data.shopName);
        this.getGroupList(response.data.shopId);
        this.open = true;
        this.title = "修改资源";
        this.limitNum = 1;
      });
    },
    //删除文件
    delFile(url){
      deleteFile(url).then(res =>{
        this.deleteFileUrl.forEach((item,index) =>{
          if (item == url){
            this.deleteFileUrl.splice(index,1)
          }
        })
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.groupList = [];
      //如果在新增操作中上传了文件没有点保存点击了取消 删除刚刚上传的文件
      if (this.form.id == undefined && this.form.resourceUrl){
        this.delFile(this.form.resourceUrl);
      }
      //判断是否是新增资源操作 如果是将删除之前 删除文件(deleteFileUrl)列表中的资源
      if (this.deleteFileUrl.length > 0 && this.form.id == undefined){
        this.deleteFileUrl.forEach((item,index) =>{
          this.delFile(item);
        })
      }
      //在修改情况下，如果点击删除操作上传一个新文件但是点了取消操作 将删除新文件地址不删除原文件地址
      if(this.form.id && this.form.resourceUrl){
        if (this.deleteFileUrl.length > 0){
          this.delFile(this.form.resourceUrl);
        }
      }

      // 判断是否是修改资源操作
      if (this.deleteFileUrl.length > 0 && this.form.id != undefined){
        this.deleteFileUrl.forEach((item,index) =>{
          //如果是修改操作点击取消将不删除最后一条数据
          if (this.deleteFileUrl.length != index +1){
            this.delFile(item);
          }
        })
      }

      this.reset()
    },
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {

          if (this.form.id != undefined) {
            resourceEdit(this.form).then(response => {
              this.msgSuccess('修改成功');
              this.delUploadList();

              this.open = false
              if (this.rolesKey == '00') {
                this.getList();

              } else {
                this.getList();
              }
            });
          } else {
            resourceAdd(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.delUploadList();
              this.open = false;
              this.merchantOpen = false;
              this.getList();
              this.reset();
            });
          }
        }
      });
    },
    //点击保存是循环删除废弃文件列表
    delUploadList(){
      //如果上传上传参数有值并且删除文件列表数量大于0的时候 将删除文件列表里面的资源
      if (this.form.resourceUrl && this.deleteFileUrl.length > 0){
        this.deleteFileUrl.forEach((item,index) =>{
          this.delFile(item);
        })
      }
    },

    //删除按钮操作
    handleDelete(row) {
      const couponId = row.id || this.ids.toString();
      this.$confirm('是否确认删除分组为"' + couponId + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return resourceDel(couponId);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    //审核按钮操作
    toExamine(row) {
      this.reset();
      const resourceId = row.id || this.ids;
      info(resourceId).then((response) => {
        this.examineForm = response.data;
        this.openExamine = true;
        this.resourceId = row.id;
        this.title = "审核";
      });
    },
    /** 资源审核通过 */
    AuditSuccess: function () {
      const resourceId = this.resourceId;
      examine({ status: 1, resourceId: resourceId }).then((response) => {
        this.openExamine = false;
        this.msgSuccess("审核通过");
        this.getList();
        // this.showbtn = false;
      });
    },
    // 驳回按钮
    turnDown() {
      const shopId = this.form.id;
      const _this = this;
      this.$prompt("请输入的驳回理由", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,50}$/,
        inputErrorMessage: "驳回内容不能小于5个字大于50个字",
      })
        .then(({ value }) => {
          examine({
            resourceId: _this.resourceId,
            status: 2,
            context: value,
          }).then((response) => {
            this.msgSuccess("驳回成功");
            this.openExamine = false;
            // this.showbtn = false;
            this.getList();
          });
        })
        .catch(() => {});
    },
    //上传文件函数
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    // 视频播放
    playVideo(row) {
      this.dialogPlay = true;
      this.url = row.resourceUrl;
    },
    closeDialog() {
      this.url = ""; //清空数据 关闭视频播放
    },
  },

};
</script>

<style scoped>
</style>
